﻿using System.Web.Mvc;
using ControleRepresentante.Data.Catalogs;
using ControleRepresentante.Logic.Models;
using ControleRepresentante.Logic.Repositories;

namespace WebSite.Controllers
{
    public class LoginController : Controller
    {
        private readonly IRepositoryProvider m_RepositoryProvider;
        private readonly ISessionConfiguration m_SessionConfiguration;

        public LoginController(IRepositoryProvider repositoryProvider, ISessionConfiguration sessionConfiguration)
        {
            m_RepositoryProvider = repositoryProvider;
            m_SessionConfiguration = sessionConfiguration;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(string usernamelogin, string passwordlogin)
        {
            IUserRepository userRepository = m_RepositoryProvider.GetRepository<IUserRepository>();
            Representante representante;
            User user = userRepository.GetUser(usernamelogin, passwordlogin, out representante);
            if (user == null)
            {
                ViewBag.Message = "Login invalido";
                return View();
            }
            if (!user.IsAdmin && representante != null && !representante.Ativo)
            {
                ViewBag.Message = string.Format("Representante '{0}' desativado", representante.Nome) ;
                return View();
            }
            if (!user.IsAdmin && representante != null && !user.Ativo)
            {
                ViewBag.Message = string.Format("Usuario '{0}' desativado", user.Username) ;
                return View();
            }
            m_SessionConfiguration.SetValue(this, "UserInfo", new UserInfo(user));
            if (representante != null)
            {
                m_SessionConfiguration.SetValue(this, "RepresentanteId", representante.Id);
                m_SessionConfiguration.SetValue(this, "RepresentanteNome", representante.Nome);
            }
            return RedirectToAction("Index", "Home");
        }

        public ActionResult Logout()
        {
            RepositoryProvider<ControleRepresentanteCatalog> repositoryProvider = m_SessionConfiguration.GetValue<RepositoryProvider<ControleRepresentanteCatalog>>(this, "RepositoryProvider");
            if (repositoryProvider != null)
            {
                repositoryProvider.Dispose();
            }
            m_SessionConfiguration.Abandon(this);
            return RedirectToAction("Index", "Home");
        }
    }
}
